package com.css.bjdt_report.executive;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mvel2.MVEL;

import com.css.bjdt_report.cell.entity.Cell;
import com.css.bjdt_report.cell.entity.CellData;
import com.css.bjdt_report.executive.report.ReportSession;
import com.css.bjdt_report.util.ReportConstant;

public class CalcExecutor extends DefaultExecutor {

	private static Log logger = LogFactory.getLog(CalcExecutor.class);

	@Override
	public String execute(Cell cell, ReportSession session) {
		List<CellData> list = (List<CellData>) session.getCellData(cell.getTemplateId());
		String calcExp = cell.getCalcExp();
		String result = "0";
		if (calcExp != null) {
			for (CellData cellData : list) {
				StringBuilder key = new StringBuilder();
				key.append("[").append(cellData.getRowNum()).append(ReportConstant.SPLIT_OPERATOR).append(cellData.getColNum()).append("]");
				if (calcExp.contains(key))
					calcExp = calcExp.replace(key, cellData.getCellValue());
			}
			try {
				result = MVEL.eval(calcExp).toString();
			} catch (Exception e) {
				logger.debug("executeExp cell id=" + cell.getCellId());
				logger.debug("error exp is " + calcExp);
			}
		}
		return result;
	}

}
